<template>
  <!-- 导入表 -->
  <el-dialog :close-on-click-modal="false" :visible.sync="visible" append-to-body title="选择用户" width="60wh">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="6" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" clearable placeholder="请输入部门名称" prefix-icon="el-icon-search"
                    size="small" style="margin-bottom: 20px"/>
        </div>
        <div class="head-container">
          <el-tree ref="tree" :data="deptOptions" :expand-on-click-node="false"
                   :filter-node-method="filterNode" :props="defaultProps" default-expand-all
                   @node-click="handleNodeClick"/>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="18" :xs="24">
        <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="queryParams.userName" clearable placeholder="请输入用户名称" size="small"
                      style="width: 150px" @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" size="mini" type="cyan" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table ref="userTable" v-loading="loading" :data="userList" :row-key="getRowKeys"
                  @select="handleTableSelect" @selection-change="handleSelectionChange"
                  @current-change="handleCurrentChange"
                  @row-click="handleRowClick">
          <el-table-column :reserve-selection="true" align="center" type="selection" :selectable="selectEnable" width="50"/>
          <el-table-column align="center" label="用户编号" prop="userId"/>
          <el-table-column :show-overflow-tooltip="true" align="center" label="用户名称" prop="userName"/>
          <el-table-column :show-overflow-tooltip="true" align="center" label="用户昵称" prop="nickName"/>
          <el-table-column :show-overflow-tooltip="true" align="center" label="部门" prop="dept.deptName"/>
        </el-table>

        <pagination v-show="total>0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum"
                    :total="total" @pagination="getList"/>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="ok">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listAllUser } from '@/api/system/user'
import { treeselect,allTreeselect } from '@/api/system/dept'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'UserDialog',
  props: {
    selectedValueStr: {
      type: String,
      required: false,
      default: ''
    },
    roleId: {
      type: Number,
      require: true
    },
    singleSelect: {
      type: Boolean,
      required: false,
      default: true
    },
    user:{
      type: Number
    },
    role: {
      type: Number
    },
  },
  data() {
    return {
      // 选中数组值
      selectedValueArr: [],
      // 选中数组显示
      selectedTextArr: [],
      // 选中数组
      selected: [],
      // 遮罩层
      visible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        roleId: null,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 保存分管领导
      shipList:[]
    }
  },
  created() {
    if (this.roleId) {
      this.queryParams.roleId = this.roleId
    }
    if (this.selectedValueStr) {
      const val = this.selectedValueStr.toString()
        if(val.length == 1){
          this.selectedValueArr = val.split("")
        }else{
          this.selectedValueArr = val.split(",")
        }
    }

    this.getList()
    this.getTreeselect()
  },
  methods: {
    /** 查询部门下拉树结构 */
    getTreeselect() {
      allTreeselect().then((response) => {
        this.deptOptions = response.data
      })
    },
    /** 筛选节点 */
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    /** 节点单击事件 */
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.getList()
    },
    /** 显示弹框 */
    show() {
      this.visible = true
      if (this.selectedValueStr && (!this.selectedValueArr || this.selectedValueArr && this.selectedValueArr.length === 0)) {
        const val = this.selectedValueStr.toString()
        if(val.length == 1){
          this.selectedValueArr = val.split("")
        }else{
          this.selectedValueArr = val.split(",")
        }
      }
      this.getList()
    },
    /** 设置选中状态 */
    setSelected() {
      let userTable = this.$refs.userTable
      if (userTable) {
        this.selectedValueArr.forEach(value => {
          this.userList.forEach(user => {
            //保证类型相同
            let userId = user.userId && user.userId instanceof String ? user.userId : user.userId.toString()

            if (value === userId) {
              userTable.toggleRowSelection(user, true)
            }
          })
        })
      }

    },
    /** 多选框选中项改变处理逻辑 */
    handleSelectionChange(selection) {
      if (this.singleSelect) {
        this.selectedValueArr = []
        this.selectedTextArr = []
        this.selected = []
        selection.forEach(item => {
          if (this.selectedValueArr.indexOf(item.userId) === -1) {
            this.selectedValueArr = []
            this.selectedTextArr = []
            this.selected = []
            this.selectedValueArr.push(item.userId)
            this.selectedTextArr.push(item.nickName)
            this.selected.push(item)
          }
        })

      } else {
          // 存储id
          this.selectedValueArr = []
          // 存储name
          this.selectedTextArr = []
          // 全部数据
          this.selected = []
          selection.forEach(item => {
            if (this.selectedValueArr.indexOf(item.userId) === -1) {
              this.selectedValueArr.push(item.userId)
              this.selectedTextArr.push(item.nickName)
              this.selected.push(item)
            }
          })
      }
    },
    /** 表格选中checkbox处理逻辑 */
    handleCurrentChange(currentRow, oldCurrentRow) {
      if (this.singleSelect) {
        this.$refs.userTable.clearSelection()
      }
    },
    /** 表格选中行处理逻辑 */
    handleTableSelect(selection, row) {
      if (this.singleSelect) {
        this.$refs.userTable.clearSelection()

        if (selection.length === 0) { // 判断selection是否有值存在
          return
        }
        this.$refs.userTable.toggleRowSelection(row, true)
      }

    },
    /** 表格点击行处理逻辑 */
    handleRowClick(row, column, event) {
      this.$refs.userTable.toggleRowSelection(row, true)
    },
    /** 查询表数据 */
    getList() {
      // 筛选当前登录用户
      if(!this.user && !this.role){
        listAllUser(this.queryParams).then(res => {
          console.log(res)
          if (res.code === 200) {
            this.userList = res.rows
            this.total = res.total
            this.loading = false
            console.log(this.userList)
            this.setSelected()
          }
        })
      }else{
        listAllUser(this.queryParams).then(res => {
          if (res.code === 200) {
            for (let i = res.rows.length -1; i >= 0; i--) {
              if(res.rows[i].userId == this.user){
                res.rows.splice(i,1)
              }
            }
            this.userList = res.rows
            this.total = res.total
            this.loading = false
            this.setSelected()
          }
        })
        this.getshipList()
      }

    },
    // 分管领导
    getshipList(){
      let params = {
        roleId: this.role,
      }
      listAllUser(params).then(res => {
        if (res.code === 200) {
          this.shipList = res.rows
        }
      })
      this.$nextTick(()=>{
        this.shipList.forEach( item =>{
          this.$refs.userTable.toggleRowSelection(item, true)
        })
      })
    },
    // 分管领导不可取消
    selectEnable(row, rowIndex) {
      if(row.roleId == this.role) {
        return false;
      }else{
        return true;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 确定 */
    ok() {
      this.visible = false
      this.$emit('dialogSelected', this.selectedValueArr, this.selectedTextArr, this.selected)
    },
    // 取消
    cancel(){
      this.visible = false
      //清空多选
      this.$refs.userTable.clearSelection()
    },
    /**获取行 key*/
    getRowKeys(row) {
      return row.userId
    }
  }
}
</script>
